package com.yb0os1.serve.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yb0os1.constant.MessageConstant;
import com.yb0os1.dto.UserLoginDTO;
import com.yb0os1.entity.Dish;
import com.yb0os1.entity.DishFlavors;
import com.yb0os1.entity.User;
import com.yb0os1.exception.LoginFailedException;
import com.yb0os1.mapper.CategoryMapper;
import com.yb0os1.mapper.DishFlavorMapper;
import com.yb0os1.mapper.DishMapper;
import com.yb0os1.mapper.UserMapper;
import com.yb0os1.properties.WeChatProperties;
import com.yb0os1.serve.UserServe;
import com.yb0os1.utils.HttpClientUtil;
import com.yb0os1.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServeImpl implements UserServe {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    private final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";


    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        // 获取openid
        String openid = getOpenID(userLoginDTO.getCode());
        // 判断openid是否为空
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断当前用户是否为新用户
        User user = userMapper.getUserByOpenid(openid);
        if (user==null){
            //新用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回对象
        return user;
    }
    //调用微信接口服务 获取openid
    private String getOpenID(String code){
        // 获取当前用户的openid 向目的地址发送请求
        Map<String,String>params = new HashMap<>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code",code);
        params.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, params);

        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
